package net.guerlab.smart.platform.user.service.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import net.guerlab.smart.platform.user.service.entity.OperationLog;
import net.guerlab.smart.platform.user.service.service.OperationLogHandler;
import net.guerlab.smart.platform.user.service.service.OperationLogService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * 操作日志处理实现
 *
 * @author guer
 */
@Component
public class OperationLogHandlerImpl implements OperationLogHandler, ApplicationContextAware {

    private OperationLogService service;

    private ObjectMapper objectMapper;

    private ApplicationContext applicationContext;

    @Async
    @Override
    public void add(String operationContent, Long userId, Object... operationParams) {
        OperationLog operationLog = new OperationLog();
        operationLog.setApplicationName(applicationContext != null ?
                applicationContext.getEnvironment().getProperty("spring.application.name") :
                null);
        operationLog.setOperationContent(operationContent);
        try {
            operationLog.setOperationParams(objectMapper.writeValueAsString(operationParams));
        } catch (Exception ignored) {
        }
        operationLog.setUserId(userId);

        service.add(operationLog);
    }

    @Autowired
    public void setService(OperationLogService service) {
        this.service = service;
    }

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @SuppressWarnings("NullableProblems")
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
